package com.coollang.smartbra.utils;

import android.text.format.DateUtils;
import android.util.Base64;
import android.util.Log;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by Administrator on 2016/10/21 0021.
 */

public class TimeUtils {

    static SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 时分秒.
     */
    public static final String dateFormatHMS = "HH:mm:ss";


    /**
     * 得到一个格式化的时间
     *
     * @param time 时间 毫秒
     * @return 时：分：秒：毫秒
     */
    public static String getFormatTime(long time) {
        time = time / 1000;
        long second = time % 60;
        long minute = (time % 3600) / 60;
        long hour = time / 3600;

        // 毫秒秒显示两位
        // String strMillisecond = "" + (millisecond / 10);
        // 秒显示两位
        String strSecond = ("00" + second).substring(("00" + second).length() - 2);
        // 分显示两位
        String strMinute = ("00" + minute).substring(("00" + minute).length() - 2);
        // 时显示两位
        String strHour = ("00" + hour).substring(("00" + hour).length() - 2);

        return strHour + ":" + strMinute + ":" + strSecond;
    }

    /**
     * 秒
     *
     * @param time
     * @return
     */
    public static String getFormatTimeHHMMSS(long time) {
        long second = time % 60;
        long minute = (time % 3600) / 60;
        long hour = time / 3600;

        // 毫秒秒显示两位
        // String strMillisecond = "" + (millisecond / 10);
        // 秒显示两位
        String strSecond = ("00" + second).substring(("00" + second).length() - 2);
        // 分显示两位
        String strMinute = ("00" + minute).substring(("00" + minute).length() - 2);
        // 时显示两位
        String strHour = ("00" + hour).substring(("00" + hour).length() - 2);

        return strHour + ":" + strMinute + ":" + strSecond;
    }

    /**
     * 得到一个格式化的时间
     *
     * @param time 时间 秒
     * @return 分：秒：秒
     */
    public static String getFormatTimemmss(long time) {
        long second = time % 60;
        long minute = (time % 3600) / 60;
        // 毫秒秒显示两位
        // String strMillisecond = "" + (millisecond / 10);
        // 秒显示两位
        String strSecond = ("00" + second).substring(("00" + second).length() - 2);
        // 分显示两位
        String strMinute = ("00" + minute).substring(("00" + minute).length() - 2);

        return strMinute + ":" + strSecond;
    }

    /**
     * 得到一个格式化的时间
     *
     * @param time 时间 秒
     * @return 分：秒：秒
     */
    public static String getFormatTimemm(long time) {
        long minute = (time % 3600) / 60;
        // 毫秒秒显示两位
        // 分显示两位
        String strMinute = ("00" + minute).substring(("00" + minute).length() - 2);

        return strMinute;
    }

    /**
     * 得到一个格式化的时间
     *
     * @param time 时间 秒
     * @return 时：分：秒：秒
     */
    public static String getFormatTimems(long time) {
        long second = time % 60;
        long minute = time - second * 60;
        // 毫秒秒显示两位
        // String strMillisecond = "" + (millisecond / 10);
        // 秒显示两位
        String strSecond = ("00" + second).substring(("00" + second).length() - 2);
        // 分显示两位
        String strMinute = ("00" + minute).substring(("00" + minute).length() - 2);

        return strMinute + "'" + strSecond + "''";
    }

    public static String getTimeFromSec(String second) {
        if (second == null || "".equals(second)) {
            return "00:00:00";
        }
        int time = Integer.parseInt(second);
        int hour = time / 3600;
        int min = (time - 3600 * hour) / 60;
        int sec = time % 60;
        return String.format("%02d:%02d:%02d", hour, min, sec);
    }

    public static String getToday() {
        SimpleDateFormat sdFormat = new SimpleDateFormat("MM-dd HH:mm");
        Date date2 = new Date(System.currentTimeMillis());
        return sdFormat.format(date2);
    }

    public static String getTodayYYYYMMDD() {
        SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date2 = new Date(System.currentTimeMillis());
        return sdFormat.format(date2);
    }

    public static String getRunTime(long time) {
        SimpleDateFormat sdFormat = new SimpleDateFormat("MM-dd HH:mm");
        Date date2 = new Date(time);
        return sdFormat.format(date2);
    }

    /**
     * @param time 毫秒
     * @return
     */
    public static String getTimeByHHmm(long time) {
        SimpleDateFormat sdFormat = new SimpleDateFormat("HH:mm");
        //        f.setTimeZone(TimeZone.getTimeZone("GTM"));
        Date date2 = new Date(time);
        return sdFormat.format(date2);
    }

    /**
     * 获取当前的时间（UNIX时间戳形式）
     *
     * @return long
     */
    public static long getCurrentTimeUnixLong() {
        return System.currentTimeMillis() / 1000;
    }

    public static String getCurrentTimeUnixString() {
        return System.currentTimeMillis() / 1000 + "";
    }

    /**
     * 将 yyyy-MM-dd HH:mm:ss 时间转化成 long 时间
     */
    public static long changeStrDateToLongDate(String strDate) {
        Date date = null;
        try {
            date = f.parse(strDate);
            return date.getTime() / 1000;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0L;
    }

    /**
     * 根据日期获得当前日期是周几
     *
     * @param yyyy-MM-dd HH:mm:ss
     * @return 1, 2, 3, 4, 5, 6, 7 周一，周二，周三，周四，周五，周六，周日
     */
    public static int getWeekByDateReturnInt(String date) {
        int year = Integer.valueOf(date.substring(0, 4));
        int month = Integer.valueOf(date.substring(5, 7));
        int day = Integer.valueOf(date.substring(8, 10));
        return getWeek(year, month, day);
    }

    /**
     * 根据日期获得当前日期是周几
     *
     * @param yyyy-MM-dd HH:mm:ss
     * @return 周一，周二，周三，周四，周五，周六，周日
     */
    public static String getWeekByDateReturnStr(String date) {
        int year = Integer.valueOf(date.substring(0, 4));
        int month = Integer.valueOf(date.substring(5, 7));
        int day = Integer.valueOf(date.substring(8, 10));
        int w = getWeek(year, month, day);
        String week = null;
        switch (w) {
            case 1:
                week = "周一";
                break;
            case 2:
                week = "周二";
                break;
            case 3:
                week = "周三";
                break;
            case 4:
                week = "周四";
                break;
            case 5:
                week = "周五";
                break;
            case 6:
                week = "周六";
                break;
            case 7:
                week = "周日";
                break;
        }
        return week;
    }

    /**
     * 获取周几
     *
     * @param year
     * @param month
     * @param day
     * @return int
     */
    public static int getWeek(int year, int month, int day) {
        if (month == 1 || month == 2) {
            month += 12;
            year--;
        }
        int w = (day + 2 * month + 3 * (month + 1) / 5 + year + year / 4 - year / 100 + year / 400) % 7;
        return w + 1;
    }

    /**
     * 获取年
     *
     * @param date 格式2016-03-28
     * @return
     */
    public static String getYear(String date) {
        return date.split("-")[0];
    }

    /**
     * 获取月
     *
     * @param date 格式2016-03-28
     * @return
     */
    public static String getMonth(String date) {
        String result;
        if (date.split("-")[1].startsWith("0")) {
            result = date.split("-")[1].split("0")[1];
        } else {
            result = date.split("-")[1];
        }
        return result;
    }

    /**
     * 获取日
     *
     * @param date 格式2016-03-28
     * @return
     */
    public static String getDay(String date) {
        String result;
        if (date.split("-")[2].startsWith("0")) {
            result = date.split("-")[2].split("0")[1];
        } else {
            result = date.split("-")[2];
        }
        return result;
    }

    /**
     * 判断是否是今天
     *
     * @param date
     * @return
     */
    public static boolean isToday(String date) {
        SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date2 = new Date();
        try {
            date2 = sdFormat.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return DateUtils.isToday(date2.getTime());
    }

    /**
     * 获取N天后的日期
     *
     * @param time
     * @param n
     * @return
     */
    public static String getNDayAfter(String time, int n, String myfm) {
        SimpleDateFormat formatDate = new SimpleDateFormat(myfm);
        Date date = null;
        try {
            date = formatDate.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (date == null) {
            return "";
        } else {
            Calendar c = Calendar.getInstance();
            c.setTimeInMillis(date.getTime());
            c.add(Calendar.DATE, n);
            return formatDate.format(c.getTime());
        }
    }

    /**
     * 获取N天前
     *
     * @param time
     * @param n
     * @return
     */
    public static String getNDayBefore(String time, int n, String myfm) {
        SimpleDateFormat formatDate = new SimpleDateFormat(myfm); // 字符串转换
        Date date = null;
        try {
            date = formatDate.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (date == null) {
            return "";
        } else {
            Calendar c = Calendar.getInstance();
            c.setTimeInMillis(date.getTime());
            c.add(Calendar.DATE, -n);// 天前的日期
            return formatDate.format(c.getTime());
        }
    }

    public static long getCurrentTimeUnixLongByDate(String dateStr) {
        //        String time="1970-01-06";//注：改正后这里前后也加了空格
        //        String time=dateStr+"00:00:01";//注：改正后这里前后也加了空格
        SimpleDateFormat format = new SimpleDateFormat(" yyyy-MM-dd HH:mm:ss ");
        String time = " " + dateStr + " 00:00:01 ";//注：改正后这里前后也加了空格" 1970-01-06 11:45:55 "
        Date date = null;
        try {
            date = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //        System.out.print("Format To times:"+date.getTime());
        return date.getTime() / 1000;
    }

    public static int getCurrentTimeZone() {
        int offset = TimeZone.getDefault().getOffset(0) / 1000;
        return offset;
    }

    /**
     * unix时间转换为北京时间
     *
     * @param secondTime
     * @return "yyyy-MM-dd"
     */
    public static String unixTimeToBeijingDate(long secondTime) {
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        return f.format(new Date(secondTime * 1000L));
    }

    /**
     * 返回8/29格式
     *
     * @param date
     * @return
     */
    public static String getString(String date) {
        return getMonth(date) + "/" + getDay(date);
    }

    /**
     * unix时间戳 转化成 北京时间
     *
     * @param secondTime long
     * @return String "yyyy-MM-dd HH:mm:ss"
     */
    public static String unixTimeToBeijingTime(long secondTime) {
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //         f.setTimeZone(TimeZone.getTimeZone("GTM"));
        return f.format(new Date(secondTime * 1000L));
    }

    public native static byte[] getFuctionCodeJNI(String mac);


    public static String unixTimeToBeijingTime(long secondTime, SimpleDateFormat f) {

        f.setTimeZone(TimeZone.getTimeZone("GTM"));
        return f.format(new java.util.Date(secondTime * 1000L));
    }

    /**
     * 将Unix时间转化为yyyyMMdd，以便于和MyDetailTable中的sign2作比较
     *
     * @param secondTime
     * @return
     */
    public static String getStrDateFormLong(long secondTime) {
        SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
        return f.format(new Date(secondTime * 1000L));
    }

    /**
     * 获取两个日期之间的间隔天数
     *
     * @return
     */
    public static int getGapCount(String start, String end, String myFm) {
        SimpleDateFormat sf = new SimpleDateFormat(myFm);
        Date startDate = null;
        Date endDate = null;
        try {
            startDate = sf.parse(start);
            endDate = sf.parse(end);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (startDate == null || endDate == null) {
            return 0;
        } else {
            Calendar fromCalendar = Calendar.getInstance();
            fromCalendar.setTime(startDate);
            fromCalendar.set(Calendar.HOUR_OF_DAY, 0);
            fromCalendar.set(Calendar.MINUTE, 0);
            fromCalendar.set(Calendar.SECOND, 0);
            fromCalendar.set(Calendar.MILLISECOND, 0);

            Calendar toCalendar = Calendar.getInstance();
            toCalendar.setTime(endDate);
            toCalendar.set(Calendar.HOUR_OF_DAY, 0);
            toCalendar.set(Calendar.MINUTE, 0);
            toCalendar.set(Calendar.SECOND, 0);
            toCalendar.set(Calendar.MILLISECOND, 0);
            return (int) ((toCalendar.getTime().getTime() - fromCalendar.getTime().getTime()) / (1000 * 60 * 60 * 24));
        }
    }

    /**
     * 获取传入的指定日期当周的  "8/10-8/17"  字符串
     *
     * @param dateStr
     * @return
     */
    public static String getWhichWeekByFormatdate(String dateStr) {
        SimpleDateFormat myFm = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = myFm.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
        String monday = "";
        String sunday = "";
        if (dayOfWeek == 1) { // 周日
            monday = unixTimeToBeijingTime(c.getTimeInMillis() / 1000 - 5 * 24 * 3600, new SimpleDateFormat("yyyy-MM-dd"));
            sunday = unixTimeToBeijingTime(c.getTimeInMillis() / 1000 + 24 * 3600, new SimpleDateFormat("yyyy-MM-dd"));
        } else {
            monday = unixTimeToBeijingTime(c.getTimeInMillis() / 1000 + (3 - dayOfWeek) * 24 * 3600, new SimpleDateFormat("yyyy-MM-dd"));
            sunday = unixTimeToBeijingTime(c.getTimeInMillis() / 1000 + (9 - dayOfWeek) * 24 * 3600, new SimpleDateFormat("yyyy-MM-dd"));
        }
        return getMonth(monday) + "/" + getDay(monday) + "-" + getMonth(sunday) + "/" + getDay(sunday);
    }

    /**
     * 一周的周几
     *
     * @param date
     * @param myFm
     * @return
     * @throws ParseException
     */
    public static int getWeekByDate(String date, String myFm) throws ParseException {
        SimpleDateFormat fm = new SimpleDateFormat(myFm);
        Date mdate = fm.parse(date);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(mdate);
        return calendar.get(Calendar.DAY_OF_WEEK);
    }

    // 比较两个时间是否是同一周 在一周
    public static boolean isInSameWeek(String firDay, String secDay, String format) {//
        if (getWhichWeek(firDay, format, null).equalsIgnoreCase(getWhichWeek(secDay, format, null))) {
            return true;
        } else {
            return false;
        }
    }

    // 传入指定格式时间字符串返回所在周的周一到周日
    public static String getWhichWeek(String dateStr, String mFormat, String tarFormat) {
        SimpleDateFormat myFm = new SimpleDateFormat(mFormat);
        if (tarFormat == null) {
            tarFormat = mFormat;
        }
        Date date = null;
        try {
            date = myFm.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
        String monday = "";
        String sunday = "";
        if (dayOfWeek == 1) { // 周日
            monday = unixTimeToBeijingTime(c.getTimeInMillis() / 1000 - 5 * 24 * 3600, new SimpleDateFormat(tarFormat));
            sunday = unixTimeToBeijingTime(c.getTimeInMillis() / 1000 + 24 * 3600, new SimpleDateFormat(tarFormat));
        } else {
            monday = unixTimeToBeijingTime(c.getTimeInMillis() / 1000 + (3 - dayOfWeek) * 24 * 3600, new SimpleDateFormat(tarFormat));
            sunday = unixTimeToBeijingTime(c.getTimeInMillis() / 1000 + (9 - dayOfWeek) * 24 * 3600, new SimpleDateFormat(tarFormat));
        }
        return monday + "-" + sunday;
    }

    private static final String IV_STRING = "alccrktkkktcertw";
    private static final String key = "tkidvnhgfloiu678";

    public static String decryptAES(String content)
            throws InvalidKeyException, NoSuchAlgorithmException,
            NoSuchPaddingException, InvalidAlgorithmParameterException,
            IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {

        byte[] encryptedBytes = Base64.decode(content, Base64.DEFAULT);

        byte[] enCodeFormat = key.getBytes();
        SecretKeySpec secretKey = new SecretKeySpec(enCodeFormat, "AES");

        byte[] initParam = IV_STRING.getBytes();
        IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);

        byte[] result = cipher.doFinal(encryptedBytes);

        return new String(result, "UTF-8");
    }

    public static byte[] decryptAESw(String content)
            throws InvalidKeyException, NoSuchAlgorithmException,
            NoSuchPaddingException, InvalidAlgorithmParameterException,
            IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {

        byte[] encryptedBytes = Base64.decode(content, Base64.DEFAULT);

        byte[] enCodeFormat = key.getBytes();
        SecretKeySpec secretKey = new SecretKeySpec(enCodeFormat, "AES");

        byte[] initParam = IV_STRING.getBytes();
        IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
        byte[] result = cipher.doFinal(encryptedBytes);
        return result;
    }

    // 传入指定格式时间字符串返回所在周的周一
    public static String getWhichWeekMonday(String dateStr, String mFormat, String tarFormat) {
        SimpleDateFormat myFm = new SimpleDateFormat(mFormat);
        if (tarFormat == null) {
            tarFormat = mFormat;
        }
        Date date = null;
        try {
            date = myFm.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
        String monday = "";
        if (dayOfWeek == 1) { // 周日
            monday = unixTimeToBeijingTime(c.getTimeInMillis() / 1000 - 5 * 24 * 3600, new SimpleDateFormat(tarFormat));
        } else {
            monday = unixTimeToBeijingTime(c.getTimeInMillis() / 1000 + (3 - dayOfWeek) * 24 * 3600, new SimpleDateFormat(tarFormat));
        }
        return monday;
    }


    /**
     * 可以将时间格式到毫秒级别
     * 00:00.00
     *
     * @param time
     * @return
     */
    public static String getFormatmillisecond(long time) {

        long millisecond = time % 1000;
        long second = (time / 1000) % 60;
        long minute = time / 1000 / 60;

        //秒以下的只显示一位
        String strMillisecond = millisecond / 10 + "";

        if (strMillisecond.length() == 1) {
            strMillisecond = "0" + strMillisecond;
        }

        //秒显示两位
        String strSecond = ("00" + second).substring(("00" + second).length() - 2);
        //分显示两位
        String strMinute = ("00" + minute).substring(("00" + minute).length() - 2);

        return strMinute + ":" + strSecond + "." + strMillisecond;
    }

    /**
     * yyyy-MM-dd HH:mm:ss 转换成为毫秒格式
     */
    public static long getLongTime(String str) {

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date sDt3 = sf.parse(str);
            return sDt3.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return 0;
    }

    public static String secToTime(int time) {
        String timeStr = null;
        int hour = 0;
        int minute = 0;
        int second = 0;
        if (time <= 0)
            return "00:00";
        else {
            minute = time / 60;
            if (minute < 60) {
                second = time % 60;
                timeStr = unitFormat(minute) + "\"" + unitFormat(second);
            } else {
                hour = minute / 60;
                if (hour > 99)
                    return "99:59:59";
                minute = minute % 60;
                second = time - hour * 3600 - minute * 60;
                timeStr = unitFormat(hour) + "\"" + unitFormat(minute) + "\"" + unitFormat(second);
            }
        }
        return timeStr;
    }

    public static String unitFormat(int i) {
        String retStr = null;
        if (i >= 0 && i < 10)
            retStr = "0" + Integer.toString(i);
        else
            retStr = "" + i;
        return retStr;
    }

    // 判断当前相差几天
    public static int differentDaysByMillisecond(long time1, long time2) {
        int days = (int) ((time2 - time1) / (3600 * 24));
        return days + 1;
    }


    // 获取今天的凌晨时间秒数
    public static long getToDayZero() {
        long current = System.currentTimeMillis();//当前时间毫秒数
        long zero = current / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();//今天零点零分零秒的毫秒数

        return zero;
        //long twelve = zero + 24 * 60 * 60 * 1000 - 1;//今天23点59分59秒的毫秒数
    }

    public static long getLastDayZero() {

        //当前时间毫秒数
        long current = System.currentTimeMillis();

        // 今天零点零分零秒的毫秒数
        long zero = current / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();

        // 今天23点59分59秒的毫秒数
        long twelve = zero + 24 * 60 * 60 * 1000 - 1;

        return twelve / 1000;
    }

    public static String getFetureDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String result = format.format(today);
        return result;
    }

    public static String getFetureDateLong(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);
        Date today = calendar.getTime();
        return today.getTime() / 1000 + "";
    }

    /**
     * 获取东八区时间
     */
    private static Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00"));

    public static int getCurrentYear() {
        return c.get(Calendar.YEAR);    //获取年
    }

    public static int getCurrentMonth() {
        return c.get(Calendar.MONTH);    //获取月
    }

    /**
     * 描述：获取表示当前日期时间的字符串.
     *
     * @param format 格式化字符串，如："yyyy-MM-dd HH:mm:ss"
     * @return String String类型的当前日期时间
     */
    public static String getCurrentDate(String format) {
        String curDateTime = null;
        try {
            SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
            Calendar c = new GregorianCalendar();
            curDateTime = mSimpleDateFormat.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return curDateTime;
    }

}
